﻿using GsOrganization.Common.Extend;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace GsOrganization.Common.Helper
{
    public static class EncryDecryHelper
    {
        /// <summary>
        /// 暂时采用一套iv和key，后续可能会根据不同的业务进行调整
        /// </summary>
        private static string AES_KEY = "zaJiVSptc0o7A7dZ";
        private static string AES_IV = "3gLrjMmGhJeEdzZg";
        #region 对称加密

        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="bsMessage"></param>
        /// <returns></returns>
        public static byte[] AES_Encrypt(this byte[] bsMessage)
        {
            if (bsMessage == null)
                return null!;
            if (bsMessage.Length == 0)
                return bsMessage;
            try
            {
                using var aes = Aes.Create();
                aes.Key = AES_KEY.UTF8BytesFromString();
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                aes.IV = AES_IV.UTF8BytesFromString();
                using var ms = new MemoryStream();
                using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(bsMessage, 0, bsMessage.Length);
                    cs.FlushFinalBlock();
                }
                return ms.ToArray();
            }
            catch
            {
                return null!;
            }
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="bsMessage"></param>
        /// <returns></returns>
        public static byte[] AES_Dencrypt(this byte[] bsMessage)
        {
            if (bsMessage == null)
                return null!;
            if (bsMessage.Length == 0)
                return bsMessage;
            try
            {
                using var aes = Aes.Create();
                aes.Key = AES_KEY.UTF8BytesFromString();
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                aes.IV = AES_IV.UTF8BytesFromString();
                using var ms = new MemoryStream();
                using (var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(bsMessage, 0, bsMessage.Length);
                    cs.FlushFinalBlock();
                }
                return ms.ToArray();
            }
            catch
            {
                return null!;
            }
        }
        #endregion

        #region 非对称加密

        #endregion
    }
}
